package cn.zf233.xcloud.config.lockpool.impl;

import cn.zf233.xcloud.config.lockpool.IXCloudThreadPool;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by zf233 on 2021/6/1
 * XCloud集群部署的线程池
 */
public class ClusterXCloudThreadPool implements IXCloudThreadPool<RLock> {

    private static final Map<Long, RLock> DOWNLOAD_LOCK_MAP = new ConcurrentHashMap<>();
    private static final Map<Long, RLock> CAPACITY_LOCK_MAP = new ConcurrentHashMap<>();

    @Resource
    private RedissonClient redissonClient;

    @Override
    public RLock getDownloadLock(Long userId) { // 获取用户对应的下载文件锁
        return DOWNLOAD_LOCK_MAP.computeIfAbsent(userId, (id) -> redissonClient.getLock(String.valueOf(id)));
    }

    @Override
    public RLock getCapacityLock(Long userId) { // 获取用户对应的容量操作锁（删除文件、上传文件等涉及到用户容量的操作）
        return CAPACITY_LOCK_MAP.computeIfAbsent(userId, (id) -> redissonClient.getLock(String.valueOf(id)));
    }

    @Override
    public RLock getMoveOrCopyLock(Long userId) { // 获取用户对应的复制、移动操作锁（删除文件、复制文件、上传文件等涉及到用户容量的操作）
        return this.getCapacityLock(userId);
    }

    @Override
    public RLock getFileRenameLock(Long userId) { // 获取用户对应的重命名文件锁（确保在重命名文件时文件不会被移除）
        return this.getCapacityLock(userId);
    }

    @Override
    public RLock getShareLock(Long userId) { // 获取用户对应的共享文件锁（确保在创建文件分享时文件不会被移除）
        return this.getCapacityLock(userId);
    }

    @Override
    public void unLock(RLock lock) {
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }

    @Override
    public void reset() { // 重置锁池
        DOWNLOAD_LOCK_MAP.clear();
        CAPACITY_LOCK_MAP.clear();
    }
}